package fr.sedoo.rbv.geonetwork.request;

import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import fr.sedoo.rbv.geonetwork.config.GeonetworkConfig;
import fr.sedoo.rbv.geonetwork.domain.GeonetworkUser;

public abstract class AuthenticatedRequest extends AbstractGeonetworkClient
{

	private GeonetworkUser user;
	protected static final String UTF8 = "UTF8";

	public AuthenticatedRequest(GeonetworkUser user) 
	{
		super();
		this.setUser(user);
	}

	public AuthenticatedRequest() 
	{
		super();
		setUser(getConfig().getAdminUser());
	}

	public AuthenticatedRequest(GeonetworkConfig config) 
	{
		super(config);
		setUser(getConfig().getAdminUser());
	}


	protected String executePostMethod(PostMethod req) throws Exception
	{
		try
		{
			String user = getUser().getLogin() + ":" + getUser().getPassword();
			byte[] encoding = Base64.encodeBase64(user.getBytes());
			req.setRequestHeader(new Header("Authorization", "Basic " + new String(encoding)));
			req.setDoAuthentication( true );	
			int result = httpclient.executeMethod(req);
			String redirectLocation;
			Header locationHeader = req.getResponseHeader("location");
			if (locationHeader != null) {
				redirectLocation = locationHeader.getValue();
				req.setPath(redirectLocation);
				result = httpclient.executeMethod(req);
			}
			if (result == HttpStatus.SC_OK) 
			{
				InputStream responseBodyAsStream = req.getResponseBodyAsStream();
				StringWriter writer = new StringWriter();
				IOUtils.copy(responseBodyAsStream, writer, "UTF8");
				String rawXml = writer.toString(); 
				return rawXml;
			}
			else
			{
				throw new Exception("Incorrect return code :"+result);
			}
		}
		catch (Exception e)
		{	
			e.printStackTrace();
			throw e;
		}
		finally {
			req.releaseConnection();
		}
	}

//	protected boolean login() {
//
//
//		Element request = new Element("request")
//		.addContent(new Element("username").setText(getUser().getLogin()))
//		.addContent(new Element("password").setText(getUser().getPassword()));
//
//		PostMethod post = new PostMethod(getConfig().getLoginURL());
//		//		post.setFollowRedirects(true);
//
//		try {
//			String postData = getString(new Document(request));
//
//			post.setRequestEntity(new StringRequestEntity(postData,
//					"application/xml", "UTF8"));
//
//			int result = httpclient.executeMethod(post);
//			if (result == HttpStatus.SC_MOVED_TEMPORARILY)
//			{
//				//				Header responseHeader = post.getResponseHeader("Location");
//				//				if (responseHeader.getValue().contains("failure=true"))
//				//				{
//				//					return false;
//				//				}
//				//				else
//				//				{
//				//					return true;
//				//				}
//				GetMethod checkRequest = new GetMethod(getConfig().getLoginCheckURL());
//				result = httpclient.executeMethod(checkRequest);
//				if (result== HttpStatus.SC_OK)
//				{
//					InputStream responseBodyAsStream = checkRequest.getResponseBodyAsStream();
//					StringWriter writer = new StringWriter();
//					IOUtils.copy(responseBodyAsStream, writer, "UTF8");
//					String rawXml = writer.toString();
//					if (rawXml.contains("false"))
//					{
//						return true;
//					}
//					return true;
//				}
//			}
//			return false;
//		}
//		catch (Exception e)
//		{	
//			e.printStackTrace();
//			return false;
//		}
//		finally {
//			post.releaseConnection();
//		}
//	}

	protected String getString(Document data)
	{
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		return outputter.outputString(data);
	}

	public GeonetworkUser getUser() {
		return user;
	}

	public void setUser(GeonetworkUser user) {
		this.user = user;
	}





}
